#!/bin/bash
sleep 2m
mkdir -p /etc/yum.repos.d/repo_bak/
mv /etc/yum.repos.d/*.repo /etc/yum.repos.d/repo_bak/
curl -o /etc/yum.repos.d/CentOS-Base.repo http://mirrors.myhuaweicloud.com/repo/CentOS-Base-7.repo
yum -y install expect
/usr/bin/expect <<EOF
spawn sh /tmp/LinuxVMDataDiskAutoInitialize.sh
expect "Step 3: Please choose the dis(e.g: /dev/vdb and q to quit):"
send "/dev/vdb\n"
expect "Please enter a location to mount (e.g: /mnt/data):"
send "/data_disk\n"
expect eof
EOF
yum install -y postgresql-server
/usr/bin/expect <<EOF
spawn pg_basebackup -h 172.16.0.10 -U dbar -D /data_disk/pgsql_data -X stream -P
expect "Password:"
send "$1\r"
expect eof
EOF
chown -R postgres.postgres /data_disk/pgsql_data
sed -i "s|/var/lib/pgsql/data|/data_disk/pgsql_data|" /usr/lib/systemd/system/postgresql.service
echo "hot_standby = on" >> /data_disk/pgsql_data/postgresql.conf
echo "max_connections = 600" >> /data_disk/pgsql_data/postgresql.conf
sed -i "s/listen_addresses = '172.16.0.10'/listen_addresses = '172.16.0.11'/g" /data_disk/pgsql_data/postgresql.conf
/usr/bin/expect <<EOF
spawn scp root@172.16.0.10:/usr/share/pgsql/recovery.conf.sample /data_disk/pgsql_data/recovery.conf
expect "Are you sure you want to continue connecting (yes/no)?"
send "yes\r"
expect "root@172.16.0.10's password:"
send "$2\r"
expect eof
EOF
echo "standby_mode = on" >> /data_disk/pgsql_data/recovery.conf
echo "primary_conninfo = 'host=172.16.0.10  port=5432 user=dbar password=$1'" >> /data_disk/pgsql_data/recovery.conf
echo "trigger_file = '/data_disk/pgsql_data/trigger.kenyon'" >> /data_disk/pgsql_data/recovery.conf
echo "recovery_target_timeline = 'latest'" >> /data_disk/pgsql_data/recovery.conf
echo "restore_command = 'cp /data_disk/pgsql_data/archivelog/%f %p'" >> /data_disk/pgsql_data/recovery.conf
echo "archive_cleanup_command = 'pg_archivecleanup /data_disk/pgsql_data/archivelog %r'" >> /data_disk/pgsql_data/recovery.conf
systemctl enable postgresql
systemctl start postgresql